import React,{useEffect, useState} from 'react';
import { Select,Input,Table,Radio,Tag,Modal,message} from 'antd';
import { useNavigate } from 'react-router-dom'
import './JoinTeam.scss'
import { useDispatch } from 'react-redux';
import {NavLink} from 'react-router-dom'
import { ExclamationCircleFilled } from '@ant-design/icons'
import {getOfOrg,getMngtable,patchMngtable,getOrglist,searchTeam,deleteTeam} from '../../../../api/Datas'

interface Props {

}
 
const { Search } = Input;
const { confirm } = Modal;
function JoinTeam(props: Props) {
    var navigate = useNavigate()
    var [truelist,setTruelist] = useState([])
    var [list,setList] = useState([])
    var [oldList, setOldList] = useState([])
    var [keyword, setKeyword] = useState('')
    var [options, setOptions] = useState([])
    var [loading, setLoading] = useState(false)
    var [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 100 })
    const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
    const [messageApi, contextHolder] = message.useMessage()
    var [options,setOptions] = useState([])
    let dispatch = useDispatch()
    // 挂载期
    useEffect(()=>{
        getManagerList()
        getmList()
            setPagination({
                ...pagination, total: list.length
            })
        
    },[])
      // 获取所属机构列表
      var getManagerList = async()=>{
        var res = await getOrglist()
        var arr = res.data.data.map((item: any) => {
            return { value: item.mechanismId, label: item.mechanismName }
        })
        setOptions(arr)

        dispatch({type:'SAVE_OFORG',payload:arr})
    }

    // 获取管理团队列表
    var getmList = async()=>{
        var res = await getMngtable()
        console.log(res)
        if(res.data.code==200){
            setLoading(false)
            setList(res.data.data[0])
            setOldList(res.data.data[0])
        }
    }
    // 点击搜索的时候
    const onSearch = async(value: string) => {
        var res = await searchTeam({name:value})
        if(res.data.code==200){
            setList(res.data.data)
            if (value!==''&&res.data.data.length) {
                message.success({ content: '查询成功' })
            } else if(value!==''&&!res.data.data.length) {
                message.warning({ content: '暂时没有此条数据' })
            }
        }
    }
 // 分页发生改变后执行
 const handleChange = (pagi:any) =>{
    setPagination(pagi) //更新页码
    setLoading(true)
    // 请求新的页码对应的数据
    getMngtable().then(res=>{
        console.log(res);
        setLoading(false)
        setPagination({
            ...pagi,total:res.data.length
        })
    })
}
      // 多选
      const rowSelection = {
        onChange: (selectedRowKeys:any, selectedRows:any)=> {
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
          setTruelist(selectedRowKeys)
        }
      }
      // 点击解散退队
      const showConfirm = (id: any) => {
        confirm({
            title: '解散确认',
            icon: <ExclamationCircleFilled />,
            content: '确定解散此团队吗?',
            okText: "确认",
            cancelText: "取消",
            onOk() {
                deleteTeam({ id }).then(res => {
                    if (res.data.code == 200) {
                        messageApi.open({
                            type: 'success',
                            content: '退队成功',
                        });
                            getmList()
                    }
                })
            },
            onCancel() {
                console.log('已取消');
            },
        });
    }

      // 表格
    const columns = [
        {
            title: '编号', //表格头的标题
            dataIndex: 'teamId', //数据索引，决定通过哪个属性名（字段名）获取数据
            key: 'teamId', 
        },
        {
            title: '头像',
            dataIndex: 'teamImg',
            key: 'teamImg',
            render:(_:any,record:any)=>{
                return (
                    <img src={record.teamImg} />
                )
            }
        },
        {
            title: '团队名称',
            dataIndex: 'teamName',
            key: 'teamName',
        },
        {
            title: '团队长',
            dataIndex: 'teamLeader',
            key: 'teamLeader',
        },
        {
            title: '团队标签',
            dataIndex: 'labelId',
            key: 'labelId',
            render: (_: any, record: any) => (
                record.labelId===1&&<Tag color='cyan' style={{ borderRadius: '20px', border: 'none' }}>慢病护理</Tag> ||
                record.labelId===2&&<Tag color='orange' style={{ borderRadius: '20px', border: 'none' }}>高血压</Tag> ||
                record.labelId===3&&<Tag color='red' style={{ borderRadius: '20px', border: 'none' }}>高血糖</Tag>||
                record.labelId===4&&<Tag color='blue' style={{ borderRadius: '20px', border: 'none' }}>冠心病</Tag>
            )
        },
        {
            title: '所属机构',
            dataIndex: 'mechanismId',
            key: 'mechanismId',
            render:(_:any,record:any)=>{
                return(
                    <p>
                        {options.map((item:any)=>item.value==record.mechanismId&&item.label)}
                    </p>
                )
            }
        },
        {
            title: '状态',
            dataIndex: 'teamState',
            key: 'teamState',
            render:(_:any,record:any)=> <span style={{color:record.teamState?"#21e121":"#ccc",fontSize :'12px'}}>{record.teamState?'启用中':'未启用'} </span>
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            render:(_:any,record:any)=>{ //动态渲染当前列的数据，和dataIndex有冲突
               return(
                <>
                    <NavLink style={{marginRight:10}} to='/index/datas-team-teamdetail' state={record.teamId}>查看详情</NavLink>
                   <a className='delete' onClick={(id) => { showConfirm(record.teamId) }}>解散退队</a>
                </>
               )
            }
        },
    ]
    // 所属机构下拉框发生变化
    var selectChange=async(value:any,option:any)=>{
        if(value){
            var arr = oldList.filter((item:any)=>item.mechanismId==value)
            setList(arr)
            if(arr.length){
                message.success({content:'查询成功'})
            }else{
                message.warning({content:'暂无数据'})
            }
        }else{
            getmList()
        } 
    }
    return (
        <div className='jointeam'>
            <div className="select">
                <span className='about'>所属机构</span>
                <div className="sleft">
                    <Select
                        allowClear
                        defaultValue="请选择"
                        style={{ width: 200 }}
                        options={options}
                        onChange={(value,option)=>{selectChange(value,option)}}
                    />
                </div>
                 <Search placeholder="请输入团队名称" onSearch={onSearch} style={{ width: 300 }} />
            </div>
            <Radio.Group
                    onChange={({ target: { value } }) => {
                        setSelectionType(value);
                    }}
                    value={selectionType}
                >
                </Radio.Group>
            <Table 
             rowSelection={{
                type: selectionType,
                ...rowSelection,
            }}
            rowKey={(record: any) => record.teamId}
            pagination={pagination}
            onChange={(pagi) => { handleChange(pagi) }}
            loading={loading}
            dataSource={list}
            columns={columns} />
        </div>
    );
}

export default JoinTeam;